package com.ruoyi.common.core.utils;

import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.IOException;

@Slf4j
public final class BASE64Util {
    public static final String encode(String base) {
        return BASE64Util.encode((byte[])base.getBytes());
    }

    public static final String encode(byte[] baseBuff) {
        return new BASE64Encoder().encode(baseBuff);
    }

    public static final String decode(String encoder) {
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] buf = decoder.decodeBuffer(encoder);
            return new String(buf);
        } catch (IOException e) {
        	log.error("decode error", e);
            return null;
        }
    }

    public static final String getTokenKey(String encoder) {
        new BASE64Util();
        String token = BASE64Util.decode((String)encoder);
        String[] strs = token.split("-");
        int i = 0;
        for (String s : strs) {
            if (++i != 1) continue;
            return s;
        }
        return null;
    }
    
    public static Long getUserId(String token){
        return Long.parseLong(BASE64Util.decode(token).split("-")[1]);
    }

    public static void main(String[] args) {
        String[] strs;
        long mills = System.currentTimeMillis();
        String str = "18263555118-123456-" + mills;
        new BASE64Util();
        String encodeAfter = BASE64Util.encode((byte[])str.getBytes());
        System.out.println(encodeAfter);
        new BASE64Util();
        System.out.println(BASE64Util.decode((String)encodeAfter));
        for (String s : strs = str.split("-")) {
            System.out.println(s);
        }
        new BASE64Util();
        System.out.println("token=" + BASE64Util.getTokenKey(encodeAfter));
    }
}

